package com.javabasic.algorithm.leetcode;

/**
 * @author mir.xiong
 * @version 1.0
 * @description
 * @see [1576. Replace All ?'s to Avoid Consecutive Repeating Characters](https://leetcode-cn.com/problems/replace-all-s-to-avoid-consecutive-repeating-characters/)
 * @since Created by work on 2022/1/5 11:04 下午
 */
public class ReplaceAllsToAvoidConsecutiveRepeatingCharacters {

    /**
     * 暴力解法+思维逻辑
     * @param s
     * @return
     */
    public String modifyString(String s) {
        char[] chars = new char[]{'a','b','c','d','e',
                'f','g','h','i','j',
                'k','l','m','n','o',
                'p','q','r','s','t',
                'u','v','w','x','y',
                'z'};
        int len = s.length(), tagLen;

        /**
         * 特殊处理
         */
        if (len == 1 && s.charAt(0) == '?') {
            return "a";
        }

        StringBuilder result = new StringBuilder();
        for (int i = 0; i < len; i++) {
            if (s.charAt(i) == '?') {
                if (i > 0 && i < len-1) {
                    for (char aChar : chars) {
                        if (s.charAt(i-1) == '?') {
                            tagLen = result.length();
                            if (aChar != result.charAt(tagLen-1) && aChar != s.charAt(i+1)) {
                                result.append(aChar);
                                break;
                            }
                        } else {
                            if (aChar != s.charAt(i-1) && aChar != s.charAt(i+1)) {
                                result.append(aChar);
                                break;
                            }
                        }
                    }
                } else if (i == 0) {
                    for (char aChar : chars) {
                        if (aChar != s.charAt(1)) {
                            result.append(aChar);
                            break;
                        }
                    }
                } else {
                    for (char aChar : chars) {
                        if (s.charAt(i-1) == '?') {
                            tagLen = result.length();
                            if (aChar != result.charAt(tagLen-1)) {
                                result.append(aChar);
                                break;
                            }
                        } else {
                            if (aChar != s.charAt(i-1)) {
                                result.append(aChar);
                                break;
                            }
                        }
                    }
                }
            } else {
                result.append(s.charAt(i));
            }
        }
        return result.toString();
    }
}
